package com.joker.demo;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class TextToSpeech {
    
    private static final String API_URL = "https://openai.qiniu.com/v1/voice/tts";
    private static final String API_KEY = "sk-05bc0a43150ec29cfe555de2ffcb22a116ff5ee5e7a234c788077d54558e3c85";
    private static final ObjectMapper mapper = new ObjectMapper();
    
    /**
     * 文本转语音 - 返回音频字节数组
     * @param text 要转换的文本
     * @param voiceType 语音类型
     * @param encoding 音频编码格式
     * @param speedRatio 语速比例
     * @return 音频字节数组
     */
    public static byte[] textToSpeech(String text, String voiceType, String encoding, double speedRatio) {
        try {
            // 构建请求对象
            TTSRequest request = new TTSRequest(
                new AudioConfig(voiceType, encoding, speedRatio),
                new RequestConfig(text)
            );
            
            String requestBody = mapper.writeValueAsString(request);
            
            // 创建HTTP请求
            HttpRequest httpRequest = HttpRequest.newBuilder()
                    .uri(URI.create(API_URL))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + API_KEY)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();
            
            // 发送请求
            HttpClient client = HttpClient.newHttpClient();
            HttpResponse<byte[]> response = client.send(
                    httpRequest, HttpResponse.BodyHandlers.ofByteArray());
            
            // 处理响应
            if (response.statusCode() == 200) {
                return response.body();
            } else {
                throw new RuntimeException("TTS请求失败: HTTP " + 
                    response.statusCode() + " - " + new String(response.body()));
            }
            
        } catch (Exception e) {
            throw new RuntimeException("文本转语音失败", e);
        }
    }
    
    /**
     * 简化版本 - 使用默认参数
     * @param text 要转换的文本
     * @return 音频字节数组
     */
    public static byte[] textToSpeech(String text) {
        return textToSpeech(
            text, 
            "qiniu_zh_female_xyqxxj",
            "mp3", 
            1.0
        );
    }
    
    /**
     * 文本转语音并保存为文件
     * @param text 要转换的文本
     * @param voiceType 语音类型
     * @param encoding 音频编码格式
     * @param speedRatio 语速比例
     * @param filePath 保存的文件路径
     */
    public static void textToSpeechFile(String text, String voiceType, String encoding, 
                                       double speedRatio, String filePath) {
        try {
            byte[] audioData = textToSpeech(text, voiceType, encoding, speedRatio);
            Path path = Paths.get(filePath);
            Files.write(path, audioData);
            System.out.println("音频文件已保存: " + path.toAbsolutePath());
        } catch (Exception e) {
            throw new RuntimeException("保存音频文件失败", e);
        }
    }
    
    /**
     * 简化版本 - 保存为文件使用默认参数
     * @param text 要转换的文本
     * @param filePath 保存的文件路径
     */
    public static void textToSpeechFile(String text, String filePath) {
        textToSpeechFile(
            text,
            "qiniu_zh_female_xyqxxj",
            "mp3",
            1.0,
            filePath
        );
    }
    
    /**
     * 获取支持的语音类型
     */
    public static class VoiceTypes {
        public static final String ZH_MALE_M392 = "zh_male_M392_conversation_wvae_bigtts";
        public static final String ZH_FEMALE_M318 = "zh_female_M318_conversation_wvae_bigtts";
        // 可以添加更多语音类型
    }
    
    /**
     * 获取支持的音频格式
     */
    public static class AudioFormats {
        public static final String MP3 = "mp3";
        public static final String WAV = "wav";
        public static final String PCM = "pcm";
    }
}

/**
 * TTS请求数据结构
 */
class TTSRequest {
    public AudioConfig audio;
    public RequestConfig request;
    
    public TTSRequest(AudioConfig audio, RequestConfig request) {
        this.audio = audio;
        this.request = request;
    }
}

/**
 * 音频配置
 */
class AudioConfig {
    public String voice_type;
    public String encoding;
    public double speed_ratio;
    
    public AudioConfig(String voice_type, String encoding, double speed_ratio) {
        this.voice_type = voice_type;
        this.encoding = encoding;
        this.speed_ratio = speed_ratio;
    }
}




/**
 * 请求配置
 */
class RequestConfig {
    public String text;
    
    public RequestConfig(String text) {
        this.text = text;
    }
}